#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash ctffind-4.1.14.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* ||  "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* ||  "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
set -e
yum install -y *wxWidget* *jpeg* *asm libtiff*

wget -t 0 -c -P $buildpath 'https://grigoriefflab.umassmed.edu/system/tdf?path=ctffind-4.1.14.tar.gz&file=1&type=node&id=26'
cd $buildpath && mv 'tdf?path=ctffind-4.1.14.tar.gz&file=1&type=node&id=26' ctffind-4.1.14.tar.gz 
tar -xf $buildpath/ctffind-4.1.14.tar.gz -C $buildpath && rm -rf $buildpath/ctffind-4.1.14.tar.gz

cd $buildpath/ctffind-4.1.14
sed -i "16c //  FLOATSINCOS(x, sin_x, cos_x);        \\\  "  src/core/matrix.cpp
sed -i "17c //  FLOATSINCOS(y, sin_y, cos_y);        \\\  " src/core/matrix.cpp
sed -i "18c //  FLOATSINCOS(z, sin_z, cos_z);        \\\  " src/core/matrix.cpp

CC=clang CXX=clang++ ./configure -prefix=$installpath/ctffind-4.1.14 CPPFLAGS="-I $installpath/fftw-3.3.10/include"
make -j 8  && make install

cat>"$installpath/ctffind-4.1.14/ctffind_modulefiles"<<EOF
#%Module1.0
conflict ctffind
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set ctffind \$pwd
setenv ctffind \$ctffind
prepend-path PATH \$ctffind/bin
EOF

rm -rf $buildpath/ctffind-4.1.14
